package com.ayf.payment.game.api.filter;

import com.alibaba.fastjson.JSON;
import com.ayf.payment.game.api.bean.ErrorBean;
import com.ayf.payment.game.api.exception.AuthorizeFailedException;
import com.ayf.payment.game.api.exception.BusinessException;
import com.ayf.payment.game.api.type.CommonConstants;
import com.swwx.charm.commons.lang.utils.LogPortal;
import com.swwx.charm.commons.lang.utils.SysContent;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 *
 *
 * @author wwl
 * @date 2020/3/4 17:01
 */
public class BasicPlatforFilter {
    //下面这些请求什么都不需要校验
    protected static final List<String> canAlwaysVisits = Arrays.asList(
            "/t/admin/login",
            "/t/merchant/export",
            "/t/merchant/orderExport",
            "/t/test/settleTset",
            "/t/merchant/getUrl",
            "/t/qq/listNetQq",
            "/t/bulletin/selectBulletin"
    );


    public boolean isContain(String uri, List<String> list) {
        boolean result = false;
        for (int i = 0; i < list.size(); i++) {
            if (uri.contains(list.get(i))) {
                result = true;
                break;
            }
        }

        return result;
    }

    public void handleException(HttpServletResponse res, Exception e) throws IOException {
        LogPortal.error("异常信息是:",e);
        ErrorBean error = null;
        if (e instanceof AuthorizeFailedException) { //授权失败
            error = new ErrorBean(CommonConstants.RETURN_ERROR, ((AuthorizeFailedException) e).getMsg());
            res.setStatus(HttpStatus.UNAUTHORIZED.value());
        }else if (e instanceof BusinessException) { //业务失败
            error = new ErrorBean(CommonConstants.RETURN_ERROR, ((BusinessException) e).getMsg());
            res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }  else {
            error = new ErrorBean(CommonConstants.RETURN_ERROR, "Server error.");
            res.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }

        res.addHeader("clueNo", SysContent.getClueNo());
        res.setHeader("Content-Type", "application/json");
        PrintWriter pw = res.getWriter();
        pw.print(JSON.toJSONString(error));
        pw.close();
    }
}
